//
//  TFVideoAreaCell.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/11.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFVideoAreaCell: UITableViewCell {
    @objc public weak var delegate : TFVideoAreaCellDelegate?
    @objc let zoomButton = UIButton()
    
    @objc let label = UILabel()
    @objc var model:TalkfunRtcModel?
    {
        didSet{
            if(model != nil)
            {
                self.update(model!)
            }
        }
    }
    //做背景透明
    @objc let scoreBackgroundColor = UIView()
    @objc let scoreButton = TFScoreButton()
    @objc let videoView = UIView()
    @objc let userButton = TFMedia()
    @objc var tempFrame:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    //进入直播间的昵称 居中比较大的
    @objc let nameLab = UILabel()
    @objc let nameContainer = UIView()
   
    //显示奖杯 YES:显示,false:隐藏
    @objc var showCup:Bool = false
    //关闭音量
    let audioStatus = UIImageView()
    //涂鸦
    let graffitiStatus = UIImageView()
    //单击手势
    @objc func dealSingleTap()
    {
       if self.delegate != nil && (self.delegate?.responds(to: #selector(TFVideoAreaCellDelegate.dealSingleTap(_:))))!{
           
           self.delegate?.dealSingleTap(self)
       }
    }
    //双击手势
    @objc func doubleTapAction()
    {
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFVideoAreaCellDelegate.objectDidDragged(_:))))!{
            
            self.delegate?.objectDidDragged(self)
        }
    }
    @objc func zoomButtonClick()
    {
        self.doubleTapAction()
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
 
        self.contentView.addSubview(self.userButton)
        self.clipsToBounds = true
        self.layer.masksToBounds = true
        //单击手势
        let singleRecognizer = self.clickGesture(target:self,action:  #selector(self.dealSingleTap))
        //双击手势
        let doubleRecognizer = self.doubleClickGesture(target:self,action:  #selector(self.doubleTapAction))
       /**
       *    双击手势确定监测失败才会触发单击手势的相应操作
       */
        singleRecognizer.require(toFail: doubleRecognizer)
        self.addSubview(self.videoView)
        
      //奖励的背景
        self.scoreBackgroundColor.isHidden = true
        self.addSubview(self.scoreBackgroundColor)

        //奖励 的 主容器
        self.scoreButton.isHidden = true
        self.scoreButton.setImage(UIImage.init(named: "HTLive.bundle/smalljiangbei"), for: .normal)
        self.scoreButton.backgroundColor = UIColor.clear
        self.addSubview(self.scoreButton)
        
        self.zoomButton.backgroundColor = UIColor(red: 13/255.0, green: 15/255.0, blue: 18/255.0, alpha: 0.6)
        self.zoomButton.isHidden = true
        self.addSubview(self.zoomButton)
        self.zoomButton.setImage(UIImage.init(named: "HTLive.bundle/shrink1vN"), for: .normal)
        self.zoomButton.addTarget(self, action: #selector(zoomButtonClick), for: .touchUpInside)

        //1.
        self.nameContainer.backgroundColor = UIColor(red: 29/255.0, green: 34/255.0, blue: 41/255.0, alpha: 0.8)

        self.addSubview(self.nameContainer)
        
        //  关闭音量
        self.audioStatus.image = UIImage.init(named: "HTLive.bundle/audioOff1vN")
        self.addSubview(self.audioStatus)
        
        //涂鸦
        self.addSubview(self.graffitiStatus)
        self.graffitiStatus.image = UIImage.init(named: "HTLive.bundle/graffiti1vN")
        self.graffitiStatus.isHidden = true
        
        self.addSubview(self.label)
        self.nameLab.textColor = UIColor.white
        self.nameLab.textAlignment = .center
        self.nameLab.isHidden = true
        self.addSubview(self.nameLab)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.userButton.frame = self.bounds
         self.zoomButton.frame = CGRect(x: self.frame.size.width-44-20, y: self.frame.size.height-44-15, width: 44, height: 44)
       
        // 超出主层边框的都会被裁减调用
         self.zoomButton.layer.masksToBounds = true
        // 圆角半径  能把一个下正文体,改成圆形
         self.zoomButton.layer.cornerRadius = 22
        self.layer.cornerRadius = 3
        self.layer.masksToBounds = true
        
        self.videoView.clipsToBounds = true
        self.videoView.layer.cornerRadius = 3
        self.videoView.layer.masksToBounds = true

        self.nameLab.frame = CGRect(x: 0, y: self.frame.size.height-30, width: self.frame.size.width, height: 20)
       
    }
    override var frame:CGRect{
            didSet {
                
                var newFrame = frame
             
                
                //重写位置
                if (frame.size.width < UIScreen.main.bounds.width-100) {
                    if self.superview != nil {
                        if self.model != nil {
                            if (self.model!.role == .roleSpadmin) {
                                newFrame.origin.y = (self.superview!.frame.size.height-(frame.size.height*2))/3.0;
                            }else if (self.model!.role == .roleeUser) {
                                newFrame.origin.y = (self.superview!.frame.size.height-(frame.size.height*2))/3.0*2+frame.size.height
                            }
                        }
                        
                        
                    }
                    
                    
                }
                
                
                super.frame = newFrame
                
     
            }
        }
    
    func update(_ model:TalkfunRtcModel)
    {
        if (model.role == .roleeUser ){
            if (self.showCup) {
                self.scoreBackgroundColor.isHidden = false;
                 self.scoreButton.isHidden = false;
            } else {
                self.scoreBackgroundColor.isHidden = true
                 self.scoreButton.isHidden = true
            }
            
        }else{
            self.scoreBackgroundColor.isHidden = true
            self.scoreButton.isHidden = true
        }
        //老师
        if (model.role == .roleSpadmin )
        {
            self.userButton.setImage(UIImage.init(named: "HTLive.bundle/jiangshi"), for: .normal)
        
        }
        //学生
        else{
            self.userButton.setImage(UIImage.init(named: "HTLive.bundle/xueyuan"), for: .normal)
           
        }

        
        //视频关闭
        if (model.role == .roleSpadmin){
            //视频与音频都关闭了
            if (model.video == .closeForZHUBO || model.video == .closeForUser ){
                
                if(model.audio == .closeForUser || model.audio == .closeForZHUBO){
                    
                    //两个都是关闭
                    self.userButton.setImage(UIImage.init(named: "HTLive.bundle/jiangshi"), for: .normal)
                    
                    self.userButton.audioModel = false;
                    self.userButton.roleType = .roleSpadmin
                    //背景色显示

                self.userButton.backgroundColorView.isHidden = true

                }else{
                    
                    //背景色隐藏

                    self.userButton.backgroundColorView.isHidden = true

                    self.userButton.audioModel = true
                    self.userButton.setImage(UIImage.init(named: "HTLive.bundle/closevideo-yinliang"), for: .normal)
                 
                    
                }
     
            }
            else{
                
                //背景色隐藏
               
                self.userButton.backgroundColorView.isHidden = true
             
                
                self.userButton.setImage(UIImage.init(named: "HTLive.bundle/jiangshi"), for: .normal)
              
                self.userButton.audioModel = false;
            }
            
        }
        else{
            
            //视频关闭了
            if(model.video == .closeForUser || model.video == .closeForZHUBO){
                
                //两个都是关闭了
                if(model.audio == .closeForUser || model.audio == .closeForZHUBO){
                    self.userButton.setImage(UIImage.init(named: "HTLive.bundle/xueyuan"), for: .normal)
                   
                    self.userButton.roleType =  .roleeUser
                    self.userButton.audioModel = false;
                    //背景色显示
                    
                        self.userButton.backgroundColorView.isHidden = true;
                  
                    
                }else{
                    
                    //背景色隐藏
                    
                    self.userButton.backgroundColorView.isHidden = true;
                  
                    self.userButton.audioModel = true
                    self.userButton.setImage(UIImage.init(named: "HTLive.bundle/closevideo-yinliang"), for: .normal)
                  
                }
                
                
            }else{
                
                //背景色隐藏
             
                self.userButton.backgroundColorView.isHidden = true
                self.userButton.setImage(UIImage.init(named: "HTLive.bundle/xueyuan"), for: .normal)
               
                self.userButton.audioModel = false
                
                
            }
            
            
            
        }

        //设置名字
        self.label.textColor = UIColor.white
        self.label.text = model.nickname as String
        if self.videoView.subviews.count>0{
            self.videoView.subviews.forEach({$0.removeFromSuperview()})
        }
       
        if (  model.isFull == false){
            
            self.videoView.addSubview(model.view)
            
            self.label.isHidden = false
        }else{
            self.label.isHidden = true
            
            
        }
        
        
        
        //视频关了
        if(model.video == .closeForUser || model.video == .closeForZHUBO){
            self.videoView.isHidden = true
        }else{
            self.videoView.isHidden = false;
            
        }
        
        
            if (model.role == .roleSpadmin) {
                
                self.label.backgroundColor = UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 0.8)
            }else{
                
                self.label.backgroundColor = UIColor(red: 29/255.0, green: 34/255.0, blue: 41/255.0, alpha: 0.8)
            }
           
     
        
        //右圆角
        let maskeight:CGFloat = 4
        let font:CGFloat = 11
        
        self.label.font = UIFont.systemFont(ofSize: font)
        let name:String = self.label.text!

        let textSize: CGSize = name.size(withAttributes: [NSAttributedString.Key.font:self.label.font])
        
        
        self.label.textAlignment = .center
        
        var labelWidth:CGFloat = textSize.width+10
        if (labelWidth > self.frame.size.width) {
            labelWidth = self.frame.size.width
        }
        self.label.textAlignment = .center
        self.label.frame = CGRect(x: 0, y: self.frame.size.height-17, width: labelWidth, height: 17)
       
        var audioStatusWidth:CGFloat = 0
        var graffitiWidth:CGFloat = 0

        if (model.role == .roleSpadmin) {
            self.graffitiStatus.isHidden = true
            self.audioStatus.isHidden = true

        } else {

            if (model.audio == .closeForZHUBO || model.audio == .closeForUser) {
                self.audioStatus.isHidden = false;
                self.audioStatus.frame = CGRect(x: labelWidth+5, y: self.frame.size.height-17, width: 17, height: 17)
                audioStatusWidth = 17+5
                graffitiWidth = 17+5+labelWidth
            } else {
                self.audioStatus.isHidden = true
                audioStatusWidth = 0
                graffitiWidth = labelWidth
            }
            if (model.drawPower) {
                self.graffitiStatus.isHidden = false;
                self.graffitiStatus.frame = CGRect(x: labelWidth+5+audioStatusWidth, y: self.frame.size.height-13.5, width: 10, height: 10)
                graffitiWidth = self.graffitiStatus.frame.origin.x+10+5
                
            } else {
                self.graffitiStatus.isHidden = true
                if (self.audioStatus.isHidden) {
                    graffitiWidth = labelWidth
                } else {
                    graffitiWidth = labelWidth + 5 + audioStatusWidth
                }
               
                
            }
            
          
        }
        

        let maskPath1 = UIBezierPath.init(roundedRect: self.label.bounds, byRoundingCorners: [.bottomLeft,.topRight], cornerRadii: CGSize(width: maskeight, height: maskeight))

        let  maskLayer1 = CAShapeLayer()
        maskLayer1.frame = self.label.bounds
        maskLayer1.path = maskPath1.cgPath

        self.label.layer.mask = maskLayer1
        self.bringSubviewToFront(self.label)
        self.bringSubviewToFront(self.nameLab)
    

        self.nameContainer.frame = CGRect(x: 0, y: self.frame.size.height-17, width: graffitiWidth, height: 17)
    
        let  maskPath2 = UIBezierPath.init(roundedRect: self.nameContainer.bounds, byRoundingCorners: [.bottomLeft,.topRight], cornerRadii: CGSize(width: maskeight, height: maskeight))
        
        let  maskLayer2 = CAShapeLayer()
        maskLayer2.frame = self.nameContainer.bounds
        maskLayer2.path = maskPath2.cgPath
        
        self.nameContainer.layer.mask = maskLayer2

        var temp:NSInteger = model.score
                  temp = temp/2
        self.scoreButton.setTitle(String.init(format: "%ld", temp), for: .normal)
       
        self.scoreButton.titleLabel!.font =  UIFont.systemFont(ofSize: font)

        let attrsSize: CGSize = String.init(format: "x%ld", temp).size(withAttributes: [NSAttributedString.Key.font: self.label.font])
         
            //19 * 0.6  j是图片宽高
               
           let scoreButtonW:CGFloat = 20*0.6+attrsSize.width
               
               self.scoreBackgroundColor.frame = CGRect(x: 0, y: 0, width: scoreButtonW+(scoreButtonW*0.4), height: 20)
        
               self.scoreBackgroundColor.backgroundColor = UIColor(red: 2/255.0, green: 11/255.0, blue: 20/255.0, alpha: 0.31)
     
               self.scoreButton.frame = self.scoreBackgroundColor.frame
        let maskPath12 = UIBezierPath.init(roundedRect: self.scoreBackgroundColor.bounds, byRoundingCorners: [.topRight,.bottomRight], cornerRadii: CGSize(width: self.scoreBackgroundColor.frame.size.height/2, height: self.scoreBackgroundColor.frame.size.height/2))
           
        
           let maskLayer12 = CAShapeLayer()
           maskLayer12.frame = self.scoreBackgroundColor.bounds
           maskLayer12.path = maskPath12.cgPath
           
        self.scoreBackgroundColor.layer.mask = maskLayer12
        self.nameLab.text = ""
         //直播已经开始 用户在线
        if ( model.view.isHidden==false) {
            self.label.isHidden = false
            self.nameLab.isHidden = true
            
            self.nameContainer.isHidden = true
        } else {
//直播已经结束的状态
            self.label.isHidden = true
            self.nameLab.isHidden = false
            
            self.nameContainer.isHidden = false
            self.nameLab.text = model.nickname

        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.setEditing(true, animated: false)
    }

}

@objc protocol TFVideoAreaCellDelegate : NSObjectProtocol {
    //双击了
    func objectDidDragged(_ model : TFVideoAreaCell)
    //单击
    func dealSingleTap(_ model : TFVideoAreaCell)
   
}
